<template>
  <div class="app-container">
    <div style="margin-bottom: 10px;">
      <el-button type="primary" icon="el-icon-edit" size="small" @click="editData(0)">添加角色</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="ID" width="95">
        <template slot-scope="scope">
          {{ scope.row.id }}
        </template>
      </el-table-column>
      <el-table-column label="角色名" align="center">
        <template slot-scope="scope">
          {{ scope.row.name }}
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.create_time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" :disabled="scope.row.id === 1" size="mini" @click="editData(scope.row.id)">
            编辑
          </el-button>
          <el-button size="mini" :disabled="scope.row.id === 1" type="danger" @click="delData(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-show="page.total > 0"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="page.total"
      :current-page.sync="page.currentPage"
      :page-size.sync="page.limit"
      :page-sizes="page.sizes"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog :title="dialogFormTitle" :visible.sync="dialogFormVisible" top="5vh" @closed="closeDialog('diaform')">
      <el-form ref="diaform" :model="form" :rules="rules">
        <el-form-item label="角色名" prop="name" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="角色菜单" :label-width="formLabelWidth">
          <el-tree
            ref="tree"
            show-checkbox
            node-key="id"
            :check-strictly="true"
            :data="allMenus"
            :current-node-key="currentkey"
            :default-checked-keys="form.menu_ids"
            :props="{ label: 'title'}"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" :loading="btnloading" @click="submitForm('diaform')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRolesList, getRolesDetail, postRoles, delRoles, getAllMenu } from '@/api/system'
const initForm = () => {
  return {
    id: 0,
    name: '',
    menu_ids: []
  }
}

export default {
  data() {
    return {
      list: [],
      listLoading: true,
      page: {
        total: 0,
        currentPage: 1,
        limit: 15,
        sizes: [15, 50, 100, 200, 500, 1000]
      },
      formLabelWidth: '120px',
      dialogFormVisible: false,
      form: initForm(),
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      allMenus: [],
      btnloading: false,
      dialogFormTitle: '新增',
      currentkey: ''
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    fetchData() {
      this.listLoading = true
      const params = {
        page: this.page.currentPage,
        limit: this.page.limit
      }
      getRolesList(params).then(response => {
        const { data } = response
        this.list = data.data
        this.page.total = data.total
        this.listLoading = false
      })
    },
    editData(id) {
      getAllMenu().then(succ => {
        this.allMenus = succ.data
      })
      if (id) {
        // 编辑
        this.dialogFormTitle = '编辑'
        // 加载数据
        this.form.id = id

        getRolesDetail(id).then(succ => {
          console.log('请求成功', succ)
          this.form = {
            ...this.form,
            ...succ.data
          }
          // 处理菜单
          if (succ.data.menu_ids !== '' && succ.data.menu_ids !== null) {
            this.form.menu_ids = succ.data.menu_ids.split(',').map(Number)
          } else {
            this.form.menu_ids = []
          }
          this.dialogFormVisible = true
        }, err => {
          console.log(err)
          // this.dialogFormVisible = false
          // this.form.id = 0
        })
      } else {
        this.dialogFormTitle = '添加'
        this.form = initForm()
        this.dialogFormVisible = true
      }
    },
    submitForm(formName) {
      this.btnloading = true
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 请求接口
          // 处理menu_ids
          this.form.menu_ids = this.$refs.tree.getCheckedKeys()
          postRoles(this.form).then(succ => {
            // 更新列表
            this.fetchData()
            this.dialogFormVisible = false
          }, err => {
            console.log('提交失败', err)
          }).finally(() => {
            this.btnloading = false
          })
        } else {
          this.btnloading = false
          return false
        }
      })
    },
    delData(row) {
      // 删除数据
      this.$confirm('确认要删除`' + row.name + '`吗？', '提示', {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 执行删除
        delRoles(row.id).then(succ => {
          this.fetchData()
          this.$message({
            type: 'success',
            message: succ.msg
          })
        })
      })
    },
    closeDialog(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.fetchData()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.fetchData()
    }
  }
}
</script>
